<!--网点维修-->
<template>
  <div>
    <!--搜索条件-->
    <el-form :inline="true">
      <el-form-item label="日期">
        <el-date-picker
          v-model="searchDto.dateSearch"
          placeholder="选择维修日期"
          value-format="yyyy-MM-dd"
          format="yyyy 年 MM 月 dd 日"
          type="date"
          :picker-options="pickDate"></el-date-picker>
      </el-form-item>
      <el-form-item size="5" v-if="roleType === '1' || roleType === '2'">
        <el-input placeholder="YSTSN" v-model="searchDto.ystsn"></el-input>
      </el-form-item>
      <el-select v-model="searchDto.pointRange" placeholder="网点范围查询"
                 v-if="roleType == '2' && officeType =='0' ">
        <el-option
          v-for="item1 in pointRangeOptions"
          :key="item1.id"
          :label="item1.name"
          :value="item1.id">
        </el-option>
      </el-select>
      <el-form-item>
        <el-button type="primary" @click="searchReturn()">查询</el-button>
      </el-form-item>
    </el-form>
    <!--tab栏-->
    <el-tabs v-model="activeName" type="card" @tab-click="handleClick">
      <el-tab-pane label="待维修" name="unrepair">
        <custom-table
          :data="acceptOrderList1"
          :columns="columns"
          :tableLoadingFlag="tableLoadingFlag1"
          :operationColumn="operationColumn1"
          :pagination="pagination1">
        </custom-table>
      </el-tab-pane>
      <el-tab-pane label="维修中" name="repairing">
        <custom-table
          :data="acceptOrderList3"
          :columns="columns"
          :tableLoadingFlag="tableLoadingFlag3"
          :operationColumn="operationColumn4"
          :pagination="pagination3">
        </custom-table>
      </el-tab-pane>
      <el-tab-pane label="已维修" name="repaired">
        <custom-table
          :data="acceptOrderList2"
          :columns="columns"
          :tableLoadingFlag="tableLoadingFlag2"
          :operationColumn="operationColumn2"
          :pagination="pagination2">
        </custom-table>
      </el-tab-pane>
    </el-tabs>
    <el-dialog :title="'创建维修工单'" center :visible.sync="repairFormVisible" wdith="100%" :close-on-click-modal="false"
               :before-close="repairCancel">
      <el-form class="form-horizontal" :rules="repairFormRule" :model="repairOrderDto" label-width="150px"
               ref="repairForm" style="text-align: left">
        <el-form-item label="sn号:">
          <el-row>
            <el-col :span="13">
              <el-input v-model.trim="device.sn" :disabled="true"></el-input>
            </el-col>
          </el-row>
        </el-form-item>
        <el-form-item label="型号:">
          <el-row>
            <el-col :span="13">
              <el-input v-model.trim="device.model" :disabled="true"></el-input>
            </el-col>
          </el-row>
        </el-form-item>
        <el-form-item label="保修截止日期" prop="expirationDate">
          <el-date-picker
            v-model="repairOrderDto.expirationDate" :disabled="device.expirationDate !== null"
            type="date"
            placeholder="选择日期"
            format="yyyy 年 MM 月 dd 日"
            value-format="yyyy-MM-dd HH:mm:ss">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="服务类型" prop="serviceType">
          <el-select placeholder="请选择服务类型" v-model="repairOrderDto.serviceType" @change="onServiceTypeChange">
            <el-option
              v-for="item in serviceTypeOptions"
              :key="item.value"
              :value="item.value"
              :label="item.label"></el-option>
          </el-select>
          <span style="color: red;margin-left: 20px" v-if="outProtection">已过保</span>
        </el-form-item>
        <el-form-item label="故障类型" prop="faultType">
          <el-select v-model="repairOrderDto.faultType" placeholder="请选择故障类型" @change="onFaultTypeChange">
            <el-option v-for="item in faultTypeOptions" :key="item.id" :value="item.id" :label="item.name"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="故障现象" prop="faultAppearance">
          <el-select v-model="repairOrderDto.faultAppearance"
                     filterable
                     placeholder="请选择故障现象代码"
                     @change="changeFaultAppearance">
            <el-option
              v-for="item in faultAppearanceOptions"
              :key="item.id"
              :label="item.code"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="用户是否同意维修" prop="isRepair"
                      v-if="repairOrderDto.serviceType === 1 || repairOrderDto.faultType === 3">
          <el-switch @change="isRepairChange()"
                     v-model="repairOrderDto.isRepair"
                     active-value="0"
                     active-text="是"
                     inactive-value="1"
                     inactive-text="否">
          </el-switch>
        </el-form-item>
        <div v-if="repairOrderDto.isRepair == 0">
          <el-form-item label="故障处理" prop="faultTreatment" v-if="repairOrderDto.faultType != 4">
            <el-select v-model="repairOrderDto.faultTreatment" placeholder="请选择故障处理方式" @change="onFaultTreatmentChange">
              <el-option
                v-for="item in repairTypeOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="合计金额" prop="totalPrice"
                        v-if="repairOrderDto.faultTreatment === 2">
            <el-input v-model.trim="repairOrderDto.totalPrice" auto-complete="off" :disabled="true" style="width:45%;">
              <template slot="append">元</template>
            </el-input>
          </el-form-item>
          <el-form-item label="选择物料" v-if="repairOrderDto.faultTreatment === 2">
            <el-button @click="addDomain" type="primary" size="small">添加物料</el-button>
          </el-form-item>
          <el-form-item v-if="repairOrderDto.faultTreatment === 2"
                        v-for="(material, index) in repairOrderDto.replacePartSubRequestList"
                        :key="index"
                        :label="'物料' + index"
                        :prop="repairOrderDto.replacePartSubRequestList[index].value"
                        :rules="{ required: true, message: '不能为空', trigger: 'blur' }">
            <el-select v-model="material.materielId" size="small"
                       @change="materialChange(index)" style="width:35%;" filterable>
              <el-option
                v-for="item in materialList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              >
              </el-option>
            </el-select>
            <el-input v-model.trim="material.price" size="small" auto-complete="off" :disable="true" style="width:30%;">
              <template slot="append">元</template>
            </el-input>
            <el-input-number placeholder="数量" :min="1" :max="50" size="small" v-model="material.num" auto-complete="off"
                             style="width:25%;"></el-input-number>
            <el-button v-if="index>0" @click.prevent="removeDomain(material)" type="danger" size="small">删除</el-button>
          </el-form-item>
          <div v-if="repairOrderDto.faultTreatment === 1">
            <el-form-item label="备机YSN" prop="ystsn">
              <el-row>
                <el-col :span="20">
                  <el-input v-model="repairOrderDto.newYstsn" auto-complete="off"></el-input>
                </el-col>
                <el-col :span="4">
                  <el-button type="primary" style="margin-left:5px;width:90%"
                             @click="searchSn(repairOrderDto.newYstsn)">搜索
                  </el-button>
                </el-col>
              </el-row>
            </el-form-item>
            <el-form-item label="更换备机型号" prop="model">
              <el-select v-model.number="repairOrderDto.newModelId" placeholder="根据备机YSN搜索获取" :disabled="true">
                <el-option
                  v-for="item in changeModelOptions"
                  :key="item.id"
                  :label="item.code"
                  :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="合计金额" prop="totalPrice"
                          v-if="repairOrderDto.serviceType === 1 || repairOrderDto.faultType === 3">
              <el-input v-model="repairOrderDto.totalPrice" auto-complete="off">
                <template slot="append">元</template>
              </el-input>
            </el-form-item>
          </div>
          <el-form-item label="合计金额" prop="totalPrice"
                        v-if="repairOrderDto.serviceType === 1 && (repairOrderDto.faultType === 2 || repairOrderDto.faultType===4)">
            <el-input v-model="repairOrderDto.totalPrice" auto-complete="off">
              <template slot="append">元</template>
            </el-input>
          </el-form-item>
          <el-form-item label="是否付款" prop="isPayment"
                        v-if="repairOrderDto.serviceType === 1 || repairOrderDto.faultType === 3">
            <el-switch @change="paymentChange()"
                       v-model="repairOrderDto.isPayment"
                       active-value="0"
                       active-text="是"
                       inactive-value="1"
                       inactive-text="否">
            </el-switch>
          </el-form-item>
          <div
            v-if="repairOrderDto.isPayment == 0 && repairOrderDto.serviceType === 1 || repairOrderDto.serviceType === 3">
            <el-form-item label="是否开发票" prop="isInvoice">
              <el-switch
                v-model="repairOrderDto.isInvoice"
                active-value="0"
                active-text="是"
                inactive-value="1"
                inactive-text="否"
                @change="getInvoice()">
              </el-switch>
            </el-form-item>
            <el-form-item label="发票类型" prop="invoiceType" v-if="repairOrderDto.isInvoice == 0 ">
              <el-select v-model="repairOrderDto.invoiceType" placeholder="请选择发票类型">
                <el-option
                  v-for="item in invoiceTypeOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="开户单位名称" v-if="repairOrderDto.isInvoice == 0 ">
              <el-input v-model.trim="repairOrderDto.companyName" auto-complete="off"></el-input>
            </el-form-item>
            <el-form-item label="税号" v-if="repairOrderDto.isInvoice == 0 ">
              <el-input v-model.trim="repairOrderDto.taxNumber" auto-complete="off"></el-input>
            </el-form-item>
            <el-form-item label="电话" v-if="repairOrderDto.isInvoice == 0 ">
              <el-input v-model.trim="repairOrderDto.tel" auto-complete="off"></el-input>
            </el-form-item>
            <el-form-item label="开户行" v-if="repairOrderDto.isInvoice == 0 ">
              <el-input v-model.trim="repairOrderDto.depositBank" auto-complete="off"></el-input>
            </el-form-item>
            <el-form-item label="开户账号" v-if="repairOrderDto.isInvoice == 0 ">
              <el-input v-model.trim="repairOrderDto.account" auto-complete="off"></el-input>
            </el-form-item>
          </div>
        </div>
        <el-form-item label="维修结果" prop="repairStatus">
          <el-select
            :disabled="repairOrderDto.isPayment == 1 || repairOrderDto.isRepair == 1 || repairOrderDto.returnFactory
            || repairOrderDto.faultType == 4 || (repairOrderDto.faultTreatment == 1 && repairOrderDto.newYstsn != '')"
            v-model="repairOrderDto.repairStatus" placeholder="请选择维修结果">
            <el-option
              v-for="item in repairStatusOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
              :disabled="item.disabled">
            </el-option>
          </el-select>
        </el-form-item>
        <el-row>
          <el-col :span="8" :offset="12">
            <el-button @click="repairCancel()">取消</el-button>
          </el-col>
          <el-col :span="4">
            <el-button type="success" @click="repairSubmit()">确定</el-button>
          </el-col>
        </el-row>
      </el-form>
    </el-dialog>
    <el-dialog :title="'维修工单详情'" center :visible.sync="detailFormVisible" width="50%"
               :close-on-click-modal="false">
      <!-- 受理工单表单 -->
      <el-form class="form-horizontal" label-width="150px" style="text-align: left">
        <el-form-item label="服务类型" prop="serviceType">
          <el-select placeholder="请选择服务类型" v-model="acceptOrderDto.serviceType" :disabled="true">
            <el-option v-for="item in serviceTypeOptions" :key="item.value" :value="item.value" :label="item.label">
              {{item.name}}
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="故障类型" prop="faultType">
          <el-select v-model="acceptOrderDto.faultTypeId" placeholder="请选择故障类型" @change="onFaultTypeChange"
                     :disabled="true">
            <el-option v-for="item in faultTypeOptions" :key="item.id" :value="item.id" :label="item.name"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="故障现象" prop="faultAppearance">
          <el-select v-model="acceptOrderDto.faultAppearance" placeholder="请选择故障现象" :disabled="true">
            <el-option
              v-for="item in faultAppearanceOptions"
              :key="item.id"
              :label="item.name"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="用户是否同意维修" prop="isRepair"
                      v-if="acceptOrderDto.serviceType === 1 || acceptOrderDto.faultType === 3">
          <el-radio-group v-model="acceptOrderDto.isRepair" :disabled="true">
            <el-radio :label="0">是</el-radio>
            <el-radio :label="1">否</el-radio>
          </el-radio-group>
        </el-form-item>
        <div v-if="acceptOrderDto.isRepair == 0">
          <el-form-item label="是否用料" prop="isMaterial" v-if="acceptOrderDto.faultType === 3">
            <el-radio-group v-model="acceptOrderDto.isMaterial" :disabled="true">
              <el-radio :label="0">是</el-radio>
              <el-radio :label="1">否</el-radio>
            </el-radio-group>
          </el-form-item>

          <el-form-item label="故障处理" prop="faultTreatment" v-if="acceptOrderDto.faultTypeId != 4">
            <el-select v-model="acceptOrderDto.faultTreatment" placeholder="请选择故障处理方式" :disabled="true">
              <el-option
                v-for="item in repairTypeOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="合计金额" prop="totalPrice"
                        v-if="acceptOrderDto.serviceType == 1 || (acceptOrderDto.serviceType == 0 && acceptOrderDto.faultTypeId == 3)">
            <el-input v-model="acceptOrderDto.totalPrice" auto-complete="off" :disabled="true">
              <template slot="append" :disabled="true">元</template>
            </el-input>
          </el-form-item>

          <el-form-item v-if="acceptOrderDto.faultTreatment == '更换部件'"
                        v-for="(material, index) in acceptOrderDto.replacePartSubRequestList"
                        :key="index"
                        :label="'物料' + index"
                        :prop="acceptOrderDto.replacePartSubRequestList[index].value">
            <el-select v-model="material.materielName" size="small"
                       style="width:35%;" filterable :disabled="true">
              <el-option
                v-for="item in materialList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              >
              </el-option>
            </el-select>
            <el-input v-model.trim="material.price" size="small" auto-complete="off" disable="true" style="width:30%;"
                      :disabled="true">
              <template slot="append">元</template>
            </el-input>
            <el-input-number placeholder="数量" :min="1" :max="50" size="small" v-model="material.num" auto-complete="off"
                             style="width:25%;" :disabled="true">
            </el-input-number>

          </el-form-item>

          <div v-if="acceptOrderDto.faultTreatmentId == 1 || acceptOrderDto.faultTreatmentId == 9">
            <el-form-item label="备机YSTSN" prop="ystsn">
              <el-row>
                <el-col :span="20">
                  <el-input v-model="acceptOrderDto.newYstsn" auto-complete="off" :disabled="true"></el-input>
                </el-col>
              </el-row>

            </el-form-item>
            <el-form-item label="备机型号" prop="model">
              <el-select v-model.number="acceptOrderDto.newModelId" placeholder="请选择型号" :disabled="true">
                <el-option
                  v-for="item in changeModelOptions"
                  :key="item.id"
                  :label="item.code"
                  :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="合计金额" prop="totalPrice"
                          v-if="acceptOrderDto.serviceType === 1 || acceptOrderDto.faultTypeId === 3">
              <el-input v-model="acceptOrderDto.totalPrice" auto-complete="off" :disabled="true">
                <template slot="append" :disabled="true">元</template>
              </el-input>
            </el-form-item>
          </div>

          <el-form-item label="是否付款" prop="isPayment"
                        v-if="acceptOrderDto.serviceType === 1 || acceptOrderDto.faultTypeId === 3">
            <el-radio-group v-model="acceptOrderDto.isPayment" :disabled="true">
              <el-radio :label="0">是</el-radio>
              <el-radio :label="1">否</el-radio>
            </el-radio-group>
          </el-form-item>

          <div v-if="acceptOrderDto.isPayment == 0">
            <el-form-item label="是否开发票" prop="isInvoice"
                          v-if="acceptOrderDto.serviceType === 1 || acceptOrderDto.faultTypeId === 3">
              <el-radio-group v-model="acceptOrderDto.isInvoice" :disabled="true">
                <el-radio :label="0">是</el-radio>
                <el-radio :label="1">否</el-radio>
              </el-radio-group>
            </el-form-item>

            <el-form-item label="发票类型" prop="invoiceType" v-if="acceptOrderDto.isInvoice == 0 ">
              <el-select v-model="acceptOrderDto.invoiceType" placeholder="请选择发票类型" :disabled="true">
                <el-option
                  v-for="item in invoiceTypeOptions"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>

            <el-form-item label="开户单位名称" v-if="acceptOrderDto.isInvoice == 0 ">
              <el-input v-model.trim="acceptOrderDto.companyName" auto-complete="off" :disabled="true"></el-input>
            </el-form-item>

            <el-form-item label="税号" v-if="acceptOrderDto.isInvoice == 0 ">
              <el-input v-model.trim="acceptOrderDto.taxNumber" auto-complete="off" :disabled="true"></el-input>
            </el-form-item>

            <el-form-item label="电话" v-if="acceptOrderDto.isInvoice == 0 ">
              <el-input v-model.trim="acceptOrderDto.tel" auto-complete="off" :disabled="true"></el-input>
            </el-form-item>

            <el-form-item label="开户行" v-if="acceptOrderDto.isInvoice == 0 ">
              <el-input v-model.trim="acceptOrderDto.depositBank" auto-complete="off" :disabled="true"></el-input>
            </el-form-item>

            <el-form-item label="开户账号" v-if="acceptOrderDto.isInvoice == 0 ">
              <el-input v-model.trim="acceptOrderDto.account" auto-complete="off" :disabled="true"></el-input>
            </el-form-item>
          </div>
        </div>

        <!--<el-input v-model.trim="totalPrice"  auto-complete="off"  disable="true" style="width:30%;" v-if="repairOrderDto.faultType === 1 || repairOrderDto.faultType === 2">>-->
        <!--<template slot="append">元</template>-->
        <!--</el-input>-->

        <el-form-item label="维修人" prop="repairer">
          <el-input v-model.trim="acceptOrderDto.repairer" auto-complete="off" :disabled="true"></el-input>
        </el-form-item>
        <el-form-item label="维修结果" prop="repairStatus">
          <el-select :disabled="true" v-model="acceptOrderDto.repairStatus" placeholder="维修结果">
            <el-option
              v-for="item in repairStatusOptions"
              :key="item.id"
              :label="item.name"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
    </el-dialog>
    <!--设备搜索一览-->
    <el-dialog title="YSTSN信息" height="300" center :visible.sync="ystsnDialogVisible"
               append-to-body :close-on-click-modal="false">
      <!-- 检索结果 -->
      <el-table
        :data="ystsnColumns"
        stripe border fit highlight-current-row>
        <el-table-column
          width="100"
          prop="productId"
          label="ID"
          v-if="false"
        >
        </el-table-column>
        <el-table-column
          width="200"
          prop="ystsn"
          label="YSTSN">
        </el-table-column>
        <el-table-column
          width="200"
          prop="modelName"
          label="型号">
        </el-table-column>
        <el-table-column
          width="100"
          prop="price"
          label="价格">
        </el-table-column>
        <el-table-column label="操作" fixed="right">
          <template slot-scope="scope">
            <el-button
              @click="checkItForYSTSN(scope.row)"
              type="text"
              size="small">
              选择
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>
  </div>
</template>

<script>
  import {apiGetFaultById} from '@/api/basic/info/fault'
  import {parseTime} from '@/utils'
  import {
    apiGetYstsnList
  } from '@/api/repairs/point/accept'
  import {apiGetFactoryList} from '@/api/basic/info/factory'
  import {apiGetRepairDetail} from '@/api/stock/index'
  import {
    apiGetFaultTypeList,
    apiGetFaultAppearanceList,
    apiGetMaterielList,
    apiGetModelList,
    apiGetFaultAppearance,
    apiGetMaterielListByModelId
  } from '@/api/dictionary'
  import {apiAddRepair, apiGetRepairList, apiGetInvoice} from '@/api/repairs/point/repair'
  import {
    getRoleType,
    getOfficeType,
    getOfficeProvinceCode,
    getOutsourceProvinceCode
  } from '@/utils/token'
  import CustomTable from '@/components/table/CustomTable'
  import Const from '@/components/contants/repairInfo'
  import {
    apiGetMaterialList
  } from '@/api/basic/info/material'

  export default {
    components: {
      CustomTable
    },
    created () {
      if (getRoleType() === '1') {
        this.operationColumn4 = this.operationColumn2
      } else if (getRoleType() === '2' || getRoleType() === '3') {
        this.operationColumn1 = this.operationColumn3
        this.operationColumn4 = this.repairColumn
      }
      this.getAcceptOrderList({})
      this.selectFaultTypeInit()
      this.getFactoryList()
    },
    data () {
      return {
        // 日期搜索限制
        pickDate: {
          disabledDate (time) {
            return time.getTime() > Date.now()
          }
        },
        // 等待数据加载
        tableLoadingFlag1: false,
        tableLoadingFlag2: false,
        tableLoadingFlag3: false,
        // 一览展示
        columns: [
          {label: 'ID', name: 'id', width: '80', align: 'center'},
          {label: '受理工单代码', name: 'acceptedCode', width: '150', align: 'center'},
          {label: '服务类型', name: 'expirationDate', width: '100', align: 'center', formatter: this.formatExpirationDate},
          {label: '状态', name: 'status', width: '100', align: 'center', formatter: this.formatStatus},
          {label: '客户所在省份', name: 'province', width: '150', align: 'center'},
          {label: '客户所在地市', name: 'city', width: '150', align: 'center'},
          {label: '客户姓名', name: 'customerName', width: '150', align: 'center'},
          {label: '联系电话', name: 'tel', width: '150', align: 'center'},
          {label: '型号', name: 'modelName', width: '150', align: 'center'},
          {label: 'YSTSN', name: 'ystsn', width: '250', align: 'center'},
          {label: '受理日期', name: 'acceptedTime', width: '160', align: 'center', formatter: this.formatTime}
        ],
        repairColumn: {
          width: '100',
          operations: [
            {name: '详细', callback: this.handleEdit},
            {name: '维修', callback: this.handelRepair}
          ]
        },
        // 操作栏
        operationColumn1: {},
        operationColumn2: {
          width: '80',
          operations: [
            {name: '详细', callback: this.handleEdit}
          ]
        },
        operationColumn3: {
          width: '80',
          operations: [
            {name: '维修', callback: this.handelRepair}
          ]
        },
        operationColumn4: {},
        // 当前tab
        tab: 0,
        // tab标签页
        activeName: 'unrepair',
        // 工单详情dto
        acceptOrderDto: {
          faultTypeId: '',
          applicationId: undefined,
          serviceType: '',
          faultAppearance: '',
          faultType: '',
          isMaterial: '',
          isRepair: '',
          faultTreatment: '',
          faultTreatmentId: undefined,
          newYstsn: '',
          productId: '',
          newModelId: '',
          repairStatus: '',
          repairer: '',
          isPayment: '',
          isInvoice: '',
          replacePartSubRequestList: [{
            materielId: '',
            price: '',
            num: undefined,
            materielName: ''
          }],
          totalPrice: undefined,
          invoiceType: undefined,
          companyName: '',
          taxNumber: '',
          tel: '',
          depositBank: '',
          account: ''
        },
        pointRangeOptions: [
          {
            'id': 0,
            'name': '当前办事处'
          },
          {
            'id': 1,
            'name': '全省范围'
          }
        ],
        // 品牌类型
        brandOptions: this.getBrandList(),
        // 客户类型查询条件一览
        customerTypeOptions: this.getCustomerTypeList(),
        // 工单详情显示
        detailFormVisible: false,
        // 维修表单展示
        repairFormVisible: false,
        // 角色类型
        roleType: getRoleType(),
        // 网点类型0:省办事处 1：市办事处
        officeType: getOfficeType(),
        // 维修表单检证
        repairFormRule: {
          expirationDate: [{required: true, message: '请选择保修截止日期', trigger: 'change'}],
          serviceType: [{required: true, message: '请选择服务类型', trigger: 'change'}],
          faultType: [{required: true, message: '请选择故障类型', trigger: 'change'}],
          faultAppearance: [{required: true, message: '请选择故障现象', trigger: 'change'}],
          faultTreatment: [{required: true, message: '请选择故障处理方式', trigger: 'change'}],
          repairStatus: [{required: true, message: '请选择维修结果', trigger: 'change'}],
          totalPrice: [{
            validator: (rule, value, callback) => {
              if (isNaN(value)) {
                callback(new Error('请输入正确数值'))
              } else {
                callback()
              }
            },
            trigger: 'blur'
          }]
        },
        // 硬件故障维修
        hardwareRepairType: Const.hardwareRepairType,
        // 软件故障维修
        softwareRepairType: Const.softwareRepairType,
        // 维修状态
        repairStatusOptions: Const.repairStatusOptions,
        // 发票类型
        invoiceTypeOptions: Const.invoiceTypeOptions,
        // 保修类型
        serviceTypeOptions: Const.serviceTypeOptions,
        // 维修信息提交dto
        repairOrderDto: {
          oldYstsn: '',
          applicationId: undefined,
          serviceType: '',
          expirationDate: '',
          faultAppearance: '',
          faultType: '',
          isMaterial: '0',
          isRepair: '0',
          faultTreatment: '',
          newYstsn: '',
          source: '', // 设备来源 0：良品库；1：报废库
          productId: '0',
          newModelId: '',
          repairStatus: '',
          isPayment: '0',
          isInvoice: '1',
          replacePartSubRequestList: [{
            materielId: '',
            price: '',
            num: 1
          }],
          totalPrice: 0,
          invoiceType: 0,
          companyName: '',
          taxNumber: '',
          tel: '',
          depositBank: '',
          account: '',
          returnFactory: false
        },
        // 维修设备信息
        device: {
          sn: '',
          model: '',
          expirationDate: ''
        },
        // 是否保外标记
        outProtection: true,
        // 故障类型
        faultTypeOptions: [],
        // 故障现象
        faultAppearanceOptions: [],
        // 维修收单一览
        acceptOrderList1: [],
        acceptOrderList2: [],
        acceptOrderList3: [],
        // 设备搜索一览
        ystsnColumns: [],
        // 设备搜索一览展示
        ystsnDialogVisible: false,
        // 条件查询dto
        searchDto: {
          dateSearch: '',
          pointRange: 0,
          ystsn: ''
        },
        // 维修类型
        repairTypeOptions: [],
        // 故障代码搜索加载
        loading: false,
        // 初始化维修dto
        initRepairOrderDto: {
          applicationId: undefined,
          oldYstsn: '',
          expirationDate: '',
          serviceType: '',
          faultAppearance: '',
          faultType: '',
          isMaterial: '0',
          isRepair: '0',
          faultTreatment: '',
          newYstsn: '',
          productId: '0',
          newModelId: '',
          repairStatus: '',
          isPayment: '0',
          isInvoice: '1',
          replacePartSubRequestList: [{
            materielId: '',
            price: '',
            num: 1
          }],
          totalPrice: 0,
          invoiceType: 0,
          companyName: '',
          taxNumber: '',
          tel: '',
          depositBank: '',
          account: ''
        },
        // 物料列表
        materialList: [],
        // 型号选择
        modelOptions: [],
        // 生产厂商
        factoryList: [],
        // 当前维修设备型号id
        repairModelId: '',
        // 备机型号选择
        changeModelOptions: this.selectedModelInit(),
        // 分页组件数据加载
        pagination1: this.getData(this.getAcceptOrderList),
        pagination2: this.getData(this.getAcceptOrderList),
        pagination3: this.getData(this.getAcceptOrderList)
      }
    },
    methods: {
      // 获取发票信息
      getInvoice () {
        if (this.repairOrderDto.isInvoice == 0) {
          apiGetInvoice(this.nextId).then(response => {
            this.repairOrderDto.account = response.data.account
            this.repairOrderDto.companyName = response.data.companyName
            this.repairOrderDto.depositBank = response.data.depositBank
            this.repairOrderDto.taxNumber = response.data.taxNumber
            this.repairOrderDto.tel = response.data.tel
          })
        }
      },

      // 条件查询
      searchReturn () {
        this.pagination1.currentPage = 1
        this.pagination1.pageSize = 10
        this.pagination2.currentPage = 1
        this.pagination2.pageSize = 10
        this.pagination3.currentPage = 1
        this.pagination3.pageSize = 10
        this.getAcceptOrderList({dateSearch: this.searchDto.dateSearch})
      },
      handleClick () {
        if (this.activeName === 'unrepair') { // 待维修标记0
          this.tab = 0
          this.getAcceptOrderList({})
        } else if (this.activeName === 'repaired') { // 已维修标记1
          this.tab = 1
          this.getAcceptOrderList({})
        } else if (this.activeName === 'repairing') { // 维修中标记2
          this.tab = 2
          this.getAcceptOrderList({})
        }
      },
      // 获取生产厂商
      getFactoryList () {
        var listQuery = {
          factoryType: 0
        }
        apiGetFactoryList(listQuery).then(response => {
          this.factoryList = response.data
        }).catch(() => {
          this.$message({showClose: true, message: '获取生产工厂列表失败', type: 'error'})
        })
      },
      // 时间格式化
      formatTime (row, column, cellValue) {
        if (column.property === 'requiredDate') {
          return parseTime(cellValue, '{y}-{m}-{d}')
        } else {
          return parseTime(cellValue)
        }
      },
      // 维修状态格式化
      formatStatus (row, column, cellValue) {
        for (let status of Const.orderStatus) {
          if (status.value === cellValue) {
            return status.label
          }
        }
        return ''
      },
      // 保内、保外格式化
      formatExpirationDate (row, column, cellValue) {
        if (cellValue !== undefined) {
          let exp = new Date(cellValue)
          let now = new Date()
          if (exp >= now) {
            return '保内'
          } else if (exp < now) {
            return '保外'
          }
        }
        return ''
      },
      // 故障代码改变事件
      changeFaultAppearance () {
        this.repairOrderDto.faultTreatment = ''
        apiGetFaultById(this.repairOrderDto.faultAppearance).then(response => {
          let type = response.data.isMaterial
          this.repairOrderDto.isMaterial = type
          if (type === 0) {                               // 硬件故障
            this.repairTypeOptions = this.hardwareRepairType   // 硬件故障处理方式
            this.selectMaterielInit()
          } else if (type === 1) {     // 软件故障
            this.repairTypeOptions = this.softwareRepairType // 软件故障处理方式
          }
        }).catch(() => {
          this.tableLoadingFlag = false
        })
      },
      // 型号选择初始化
      selectedModelInit () {
        apiGetModelList().then(response => {
          let modelList = response.data
          let model = []
          let temp = {}
          for (let i in modelList) {
            if (!temp[modelList[i].code]) {
              temp[modelList[i].code] = modelList[i].id
            }
          }
          model.push({'code': '全部型号', 'value': ''})
          for (let k in temp) {
            model.push({'code': k, 'id': temp[k]})
          }
          this.changeModelOptions = model
        }).catch(() => {
          this.tableLoadingFlag = false
        })
      },
      // 物料选择初始化
      selectMaterielInit () {
        apiGetMaterielList().then(response => {
          let materielList = response.data
          let materiel = []
          let temp = {}
          for (let i in materielList) {
            if (!temp[materielList[i].name]) {
              temp[materielList[i].name] = materielList[i].id
            }
          }
          for (let k in temp) {
            materiel.push({'name': k, 'id': temp[k]})
          }
          this.materielOptions = materiel
        }).catch(() => {
          this.tableLoadingFlag = false
        })
      },
      // 故障现象初始化
      selectFaultAppearanceInit (type) {
        let listQuery = {
          faultType: type
        }
        apiGetFaultAppearanceList(listQuery).then(response => {
          let faultAppearanceList = response.data
          let faultAppearance = []
          let temp = {}
          for (let i in faultAppearanceList) {
            if (!temp[faultAppearanceList[i].name]) {
              temp[faultAppearanceList[i].name] = faultAppearanceList[i].id
            }
          }
          for (let k in temp) {
            faultAppearance.push({'name': k, 'id': temp[k]})
          }
          this.faultAppearanceOptions = faultAppearance
        }).catch(() => {
          this.tableLoadingFlag = false
        })
      },
      // 故障类型选择初始化
      selectFaultTypeInit () {
        apiGetFaultTypeList().then(response => {
          let faultTypeList = response.data
          let faultType = []
          let temp = {}
          for (let i in faultTypeList) {
            if (!temp[faultTypeList[i].name]) {
              temp[faultTypeList[i].name] = faultTypeList[i].id
            }
          }
          for (let k in temp) {
            faultType.push({'name': k, 'id': temp[k]})
          }
          this.faultTypeOptions = faultType
        }).catch(() => {
          this.tableLoadingFlag = false
        })
      },
      // 服务类型改变事件
      onServiceTypeChange () {
        let serviceType = this.repairOrderDto.serviceType
        if (this.repairOrderDto.serviceType === 1) {
          this.outProtection = true
        } else {
          this.outProtection = false
        }
        this.initRepairOrderDto.expirationDate = this.repairOrderDto.expirationDate
        let sn = this.repairOrderDto.oldYstsn
        this.repairOrderDto = this.initRepairOrderDto
        this.repairOrderDto.serviceType = serviceType
        this.repairOrderDto.oldYstsn = sn
      },
      // 故障类型改变事件
      onFaultTypeChange (type) {
        this.repairOrderDto.faultType = type
        this.repairOrderDto.faultAppearance = ''
        this.repairOrderDto.faultTreatment = ''
        this.repairOrderDto.newYstsn = ''
        this.repairOrderDto.newModelId = ''
        this.repairOrderDto.totalPrice = ''
        let listQuery = {
          faultType: this.repairOrderDto.faultType,
          typeId: ''
        }
        apiGetFaultAppearance(listQuery).then(response => {
          let appearList = response.data
          let appear = []
          let temp = {}
          for (let i in appearList) {
            if (!temp[appearList[i].appearance]) {
              temp[appearList[i].appearance] = appearList[i].id
            }
          }
          for (let k in temp) {
            appear.push({'code': k, 'id': temp[k]})
          }
          this.faultAppearanceOptions = appear
        }).catch(() => {
          this.tableLoadingFlag = false
        })
        if (this.repairOrderDto.serviceType === 0 && this.repairOrderDto.faultType === 1) {
          this.hardwareRepairType = Const.hardwareRepairType2
        } else {
          this.hardwareRepairType = Const.hardwareRepairType
        }
        this.repairTypeOptions = []
        this.repairOrderDto.returnFactory = false
        this.repairOrderDto.repairStatus = ''
        if (this.repairOrderDto.faultType === 4) {
          this.repairOrderDto.repairStatus = 2
        }
      },
      // 是否同意维修
      isRepairChange () {
        if (this.repairOrderDto.isRepair === '1') {
          this.repairOrderDto.repairStatus = 3     // 原物返还
        } else {
          this.repairOrderDto.repairStatus = ''
        }
      },
      // 是否同意支付
      paymentChange () {
        if (this.repairOrderDto.isPayment === '1') {  // 不同意支付
          this.repairOrderDto.repairStatus = 1     // 待修复
        } else {
          this.repairOrderDto.repairStatus = ''
        }
      },
      // 删除物料
      removeDomain (item) {
        var index = this.repairOrderDto.replacePartSubRequestList.indexOf(item)
        if (index !== -1) {
          this.repairOrderDto.replacePartSubRequestList.splice(index, 1)
        }
      },
      // 添加物料
      addDomain () {
        var _that = this
        if (this.repairOrderDto.replacePartSubRequestList.length >= 8) {
          _that.$message({showClose: true, message: '最多添加8项物料', type: 'error'})
        } else {
          this.repairOrderDto.replacePartSubRequestList.push({
            materielId: '',
            price: '',
            num: 1
          })
        }
      },
      // 获取物料一览
      getMaterialList () {
        apiGetMaterielListByModelId(this.repairModelId).then(response => {
          this.materialList = response.data
        }).catch(() => {
          this.tableLoadingFlag = false
        })
      },
      // 物料改变事件
      materialChange (index) {
        var val = this.repairOrderDto.replacePartSubRequestList[index].materielId
        var res = this.materialList.find(d => d.id === val)
        this.repairOrderDto.replacePartSubRequestList[index].price = res.price
      },
      // 提交维修信息
      repairSubmit () {
        var flag = false
        this.$refs['repairForm'].validate((valid) => {
          if (this.repairOrderDto.faultTreatment === 2 && this.repairOrderDto.isMaterial === 0) {
            for (let part in this.repairOrderDto.replacePartSubRequestList) {
              if (!this.repairOrderDto.replacePartSubRequestList[part].materielId) {
                flag = true
              }
            }
          }
          if (flag) {
            this.$message({
              showClose: true,
              message: '请填写物料'
            })
          } else if (valid) {
            this.repairOrderDto.applicationId = this.nextId
            apiAddRepair(this.repairOrderDto).then(response => {
              var _type = response.resCode === '200' ? 'success' : 'error'
              this.$message({
                showClose: true,
                message: response.message,
                type: _type
              })
              this.repairOrderDto = this.initRepairOrderDto
              this.getAcceptOrderList({})
            })
          } else {
            return false
          }
          this.cancel('repairForm', 3)
        })
        if (!flag) {
          this.repairOrderDto = this.initRepairOrderDto
        }
      },
      // 设备维修
      handelRepair (row) {
        this.device.model = row.modelName
        this.device.sn = row.ystsn
        this.device.expirationDate = row.expirationDate
        this.repairOrderDto.expirationDate = row.expirationDate
        this.repairModelId = row.modelId
        this.repairOrderDto.oldYstsn = row.ystsn
        this.nextId = row.id
        this.repairFormVisible = true
        if (row.expirationDate !== undefined && row.expirationDate !== null) {
          let exp = new Date(row.expirationDate)
          let now = new Date()
          if (exp >= now) {
            this.repairOrderDto.serviceType = 0
            this.outProtection = false
          } else if (exp < now) {
            this.repairOrderDto.serviceType = 1
            this.outProtection = true
          } else {
          }
        } else {
          this.repairOrderDto.serviceType = ''
          this.outProtection = false
        }
        this.$nextTick(() => {
          this.$refs['repairForm'].resetFields()
        })
      },
      // 获取维修数据一览
      getAcceptOrderList (listQuery) {
        if (listQuery !== undefined) {
          if (this.tab === 0) { // 待维修
            listQuery.repairStatus = 0
            this.tableLoadingFlag1 = true
          } else if (this.tab === 2) { // 维修中
            listQuery.repairStatus = 2
            this.tableLoadingFlag3 = true
          } else if (this.tab === 1) { // 已维修
            listQuery.repairStatus = 3
            this.tableLoadingFlag2 = true
          }
        }
        if (getRoleType() === '2') {
          listQuery.provinceCode = getOfficeProvinceCode()
        }
        if (getRoleType() === '3') {
          listQuery.provinceCode = getOutsourceProvinceCode()
        }
        if (this.officeType !== 'undefined') {
          listQuery.officeType = this.officeType
        } else {
          listQuery.officeType = ''
        }
        listQuery.dateSearch = this.searchDto.dateSearch
        listQuery.pointRange = this.searchDto.pointRange
        listQuery.ystsn = this.searchDto.ystsn
        apiGetRepairList(listQuery).then(response => {
          if (listQuery.repairStatus === 0) {
            this.acceptOrderList1 = response.data
            this.pagination1.totalRecords = response.totalRecords
            this.tableLoadingFlag1 = false
          } else if (listQuery.repairStatus === 3) {
            this.acceptOrderList2 = response.data
            this.pagination2.totalRecords = response.totalRecords
            this.tableLoadingFlag2 = false
          } else if (listQuery.repairStatus === 2) {
            this.acceptOrderList3 = response.data
            this.pagination3.totalRecords = response.totalRecords
            this.tableLoadingFlag3 = false
          }
        }).catch(() => {
          this.tableLoadingFlag = false
        })
      },
      // 对话框关闭
      cancel (formName, nextFlag) {
        if (nextFlag === 1) {
        } else {
          if (nextFlag === 3) {
            this.repairFormVisible = false
          }
          this.getAcceptOrderList({pageNumber: this.pagination.currentPage, pageSize: this.pagination.pageSize})
          if (this.$refs[formName] !== undefined) {
            this.$refs[formName].resetFields()
          }
        }
      },
      // 根据sn搜索设备
      searchSn (value) {
        let ystsnDto = {
          ystsn: value
        }
        apiGetYstsnList(ystsnDto).then(response => {
          this.ystsnColumns = response.data
          this.ystsnDialogVisible = true
        })
      },
      // 选择设备
      checkItForYSTSN (row) {
        this.repairOrderDto.newYstsn = row.ystsn
        this.repairOrderDto.newModelId = row.modelId
        this.repairOrderDto.productId = row.productId
        this.repairOrderDto.totalPrice = row.price
        this.repairOrderDto.source = row.source
        // 更换备机后状态改为已修复
        this.repairOrderDto.repairStatus = 2
        this.ystsnDialogVisible = false
      },
      // 取消维修
      repairCancel () {
        this.repairFormVisible = false
        this.repairOrderDto.isRepair = '0'
        this.repairOrderDto.isMaterial = '0'
        this.repairOrderDto.isPayment = '0'
        this.repairOrderDto.faultAppearance = ''
        // this.isInvoice = '1'
        this.repairOrderDto.replacePartSubRequestList = [{
          materielId: '',
          price: '',
          num: ''
        }]
        this.repairOrderDto = this.initRepairOrderDto
        this.$refs['repairForm'].resetFields()
      },
      // 故障处理方式改变事件
      onFaultTreatmentChange () {
        this.repairOrderDto.newYstsn = ''
        this.repairOrderDto.newModelId = ''
        this.repairOrderDto.totalPrice = ''
        this.repairOrderDto.replacePartSubRequestList = [{
          materielId: '',
          price: '',
          num: 1
        }]
        if (this.repairOrderDto.faultTreatment === 2) {
          this.getMaterialList()
        }
        if (this.repairOrderDto.serviceType === 1 && (this.repairOrderDto.faultType === 2 || this.repairOrderDto.faultType === 4)) {
          let listQuery = {
            name: ''
          }
          if (this.repairOrderDto.faultTreatment === 3) {
            listQuery.name = '刷机'
          } else if (this.repairOrderDto.faultTreatment === 4) {
            listQuery.name = '升级'
          } else if (this.repairOrderDto.faultTreatment === 5) {
            listQuery.name = '恢复出厂设置'
          }
          apiGetMaterialList(listQuery).then(response => {
            if (response.data !== null) {
              this.repairOrderDto.totalPrice = response.data[0].consumerPrice
            }
          })
        }
        // 如果是原机返厂
        if (this.repairOrderDto.faultTreatment === 8) {
          this.repairOrderDto.repairStatus = 7
          this.repairOrderDto.returnFactory = true
        } else {
          this.repairOrderDto.returnFactory = false
        }
      },
      getModelList (brandId) {
        apiGetModelList(brandId).then(response => {
          this.modelOptions = response.data
        })
      },
      // 工单详情
      handleEdit (row) {
//        this.nextId = row.id
        this.detailFormVisible = true
        let listQuery = {
          applicationId: row.id
        }
        apiGetRepairDetail(listQuery).then(response => {
          this.acceptOrderDto = response.data
          if (response.data.isInvoice !== undefined) {
            let isInvoice = parseInt(response.data.isInvoice)
            this.acceptOrderDto.isInvoice = isInvoice
          }
          if (response.data.isPayment !== undefined) {
            let isPayment = parseInt(response.data.isPayment)
            this.acceptOrderDto.isPayment = isPayment
          }
          if (response.data.isRepair !== undefined) {
            let isRepair = parseInt(response.data.isRepair)
            this.acceptOrderDto.isRepair = isRepair
          }
        }).catch(() => {
        })
      }
    },
    watch: {
      'repairOrderDto.replacePartSubRequestList': {
        handler (curVal) {
          let totalPrice = 0
          for (let i in curVal) {
            totalPrice += curVal[i].price * curVal[i].num
          }
          this.repairOrderDto.totalPrice = totalPrice.toFixed(2)
        },
        deep: true
      }
    }
  }
</script>
